package com.learning.concurrency;

import com.learning.concurrency.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Created By kane at 2018/12/19 11:48 AM
 */

@Slf4j
@NotThreadSafe
public class ConcurrencyTest {

    // 请求总数
    public static int clientTotal = 5000;

    // 同时并发的线程数
    public static int threadTotal = 200;

    // 计数
    public static int count = 0;

    /**
     * 模拟5000次请求在并发量200的基础上的线程安全问题
     * 该测试说明：在并发下由于 ++ 操作不具备原子性导致的并发安全问题
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception{
        // 线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 信号量
        final Semaphore semaphore = new Semaphore(threadTotal);
        // countDownLatch
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        // 模拟请求
        for (int i = 0, len = clientTotal; i < len; i++) {
            // 使用线程池
            executorService.execute(() -> {
                try {
                    // 信号量获取许可
                    semaphore.acquire();
                    // 调用add
                    add();
                    // 信号量释放许可
                    semaphore.release();
                } catch (Exception e) {
                    log.error("Exception", e);
                }
                // countDownLatch的线程countDown操作
                countDownLatch.countDown();
            });
        }
        // countDownLatch的主线程await操作
        countDownLatch.await();
        // 线程池释放资源
        executorService.shutdown();
        log.info("count:{}", count);

    }

    private static void add() {
        count++;
    }

}
